import os
import threading

from PyQt5 import QtCore, Qt
from PyQt5.QtWidgets import QLabel, QHBoxLayout, QFileDialog
from qfluentwidgets import MessageBoxBase, SubtitleLabel, LineEdit, PushButton, InfoBar, InfoBarPosition

from ..utils.checkDevLanguageVersion import checkPathValid


class ConfigPathMessageBox(MessageBoxBase):
    """ 配置路径消息框 """

    def __init__(self, devLanguage: object, parent=None):
        super().__init__(parent)
        self.devLanguage = devLanguage
        self.titleLabel = SubtitleLabel(devLanguage.name + self.tr('语言路径配置'), self)
        self.pathLineEdit = LineEdit(self)
        self.pathLineEdit.setMinimumWidth(300)
        self.pathLineEdit.setPlaceholderText(self.tr('选择或输入路径'))
        self.pathLineEdit.setClearButtonEnabled(True)

        self.selectButton = PushButton(self.tr('选择文件夹'), self)
        self.tipLabel = QLabel("", self)
        self.tipErrorLabel = QLabel("", self)
        self.tipErrorLabel.setStyleSheet("color: red")
        # 隐藏tipLabel
        self.tipLabel.setVisible(False)
        self.tipErrorLabel.setVisible(False)

        # 创建一个水平布局
        self.hBoxLayout = QHBoxLayout()
        self.hBoxLayout.addWidget(self.pathLineEdit)
        self.hBoxLayout.addWidget(self.selectButton)

        self.viewLayout.addWidget(self.titleLabel)
        self.viewLayout.addLayout(self.hBoxLayout)
        self.viewLayout.addWidget(self.tipLabel)
        self.viewLayout.addWidget(self.tipErrorLabel)

        # 更改按钮的文本
        self.yesButton.setText(self.tr('确定'))
        self.yesButton.setDisabled(True)  # 设置按钮不可用
        self.cancelButton.setText(self.tr('取消'))

        self.widget.setMinimumWidth(360)  # 设置消息框最小宽度
        self.pathLineEdit.textChanged.connect(self._onPathTextChanged)  # 监听文本框内容变化
        self.selectButton.clicked.connect(self.__onSelectButtonClicked)

        if devLanguage.env_var_value:
            self.pathLineEdit.setText(devLanguage.env_var_value)

    def __showTipErrorLabel(self, content):
        QtCore.QMetaObject.invokeMethod(self.tipLabel, "setVisible", QtCore.Qt.QueuedConnection,
                                        QtCore.Q_ARG(bool, False))
        QtCore.QMetaObject.invokeMethod(self.tipErrorLabel, "setVisible", QtCore.Qt.QueuedConnection,
                                        QtCore.Q_ARG(bool, True))
        QtCore.QMetaObject.invokeMethod(self.tipErrorLabel, "setText", QtCore.Qt.QueuedConnection,
                                        QtCore.Q_ARG(str, content))
        QtCore.QMetaObject.invokeMethod(self.yesButton, "setDisabled", QtCore.Qt.QueuedConnection,
                                        QtCore.Q_ARG(bool, True))

    def __showTipLabel(self, content):
        QtCore.QMetaObject.invokeMethod(self.tipLabel, "setVisible", QtCore.Qt.QueuedConnection,
                                        QtCore.Q_ARG(bool, True))
        QtCore.QMetaObject.invokeMethod(self.tipErrorLabel, "setVisible", QtCore.Qt.QueuedConnection,
                                        QtCore.Q_ARG(bool, False))
        QtCore.QMetaObject.invokeMethod(self.tipLabel, "setText", QtCore.Qt.QueuedConnection,
                                        QtCore.Q_ARG(str, content))
        QtCore.QMetaObject.invokeMethod(self.yesButton, "setDisabled", QtCore.Qt.QueuedConnection,
                                        QtCore.Q_ARG(bool, False))

    def _onPathTextChanged(self, path):
        if path and path != "":
            self.__startCheckLanguageThread(path)

    def __startCheckLanguageThread(self, path):
        self.__stopCheckLanguageThread()
        self._checkLanguageThread = threading.Thread(target=self.__checkLanguageForPath, args=(path,))
        self._checkLanguageThread.start()

    def __stopCheckLanguageThread(self):
        if hasattr(self, "_checkLanguageThread") and self._checkLanguageThread.is_alive():
            self._checkLanguageThread.join()

    def __checkLanguageForPath(self, path):
        try:
            version = self.devLanguage.checkIsSameLanguage(path)
            if version:
                self.devLanguage.env_var_value = checkPathValid(path)
                self.__showTipLabel(f'语言类型: {self.devLanguage.name}, 版本: {version}')
            else:
                path_env_var_suffix_str = "、".join(self.devLanguage.path_env_var_suffix)
                self.__showTipErrorLabel(f"请选择正确的语言路径。请注意：路径中不应包含 {path_env_var_suffix_str} 目录。")
        except FileNotFoundError as fnfe:
            error_content = str(fnfe)
            self.__showTipErrorLabel(error_content)
        except Exception as e:
            self.showTipErrorLabel(e.__str__())

    def __onSelectButtonClicked(self):
        try:
            path = QFileDialog.getExistingDirectory(self, self.tr("选择语言路径"))
            path = checkPathValid(path)
            self.pathLineEdit.setText(path)
        except FileNotFoundError as e:
            InfoBar.error(
                title='出错啦！',
                content=e.__str__(),
                orient=Qt.Vertical,
                isClosable=True,
                position=InfoBarPosition.BOTTOM_RIGHT,
                duration=3000,
                parent=self.parent()
            )
